﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for PropertyGridWindow.xaml
    /// </summary>
    public partial class PropertyGridWindow : Window
    {
        public event EventHandler<PropertyChangedEventArgs> PropertyChanged;

        public static readonly DependencyProperty InstanceProperty =
            DependencyProperty.Register("Instance", typeof(object), typeof(PropertyGridWindow), new PropertyMetadata(null, OnInstanceChanged));

        public object Instance
        {
            get { return (object)GetValue(InstanceProperty); }
            set { SetValue(InstanceProperty, value); }
        }

        private static void OnInstanceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PropertyGridWindow source = d as PropertyGridWindow;

            object v = e.NewValue as object;
            object vOld = e.OldValue as object;

            source.UpdateInstance(v, vOld);
        }

        private void UpdateInstance(object viewModel, object viewModelOld)
        {
            Instance = viewModel;
            var notifyNew = viewModel as INotifyPropertyChanged;
            bool same = false;

            if (viewModelOld != null)
            {
                var notifyOld = viewModelOld as INotifyPropertyChanged;

                if (viewModelOld != viewModel)
                {
                    same = true;
                    notifyOld.PropertyChanged -= notifyNew_PropertyChanged;
                }
            }

            if (!same)
            {
                notifyNew.PropertyChanged += new PropertyChangedEventHandler(notifyNew_PropertyChanged);
            }

            this.DataContext = viewModel;
            this.InvalidateVisual();
        }

        void notifyNew_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }

        public PropertyGridWindow()
        {
            InitializeComponent();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
                e.Handled = true;
            }
        }
    }
}
